<script setup>
import { ref, onMounted } from 'vue'
import { pageQueryUser, saveUser, deleteUser, getUser, updateUser } from '@/api/user.js'
import { Message } from '@arco-design/web-vue'

const pageForm = ref({
  id: '',
  nickname: '',
  userRole: '',
  beginTime: '',
  endTime: '',
  currentPage: 1,
  pageSize: 10
})
const pageFormRef = ref()
const total = ref(0)
const createTime = ref()
const tableLoading = ref(false)
const tableData = ref([])

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    ellipsis: true,
    tooltip: true,
    fixed: 'left',
    width: 190
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '状态',
    dataIndex: 'userStatus',
    ellipsis: true,
    tooltip: true,
    slotName: 'userStatusSlot',
    width: 100
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    ellipsis: true,
    tooltip: true,
    slotName: 'userRole',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 180
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    slotName: 'optional',
  }
]

const selectedKeys = ref([])
const rowSelection = ref({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false
})

// 新增用户相关
const addVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  email: '',
  nickname: '',
  userRole: '',
  userStatus: '0' // 默认正常状态
})

// 编辑用户相关
const editVisible = ref(false)
const editFormRef = ref()
const editForm = ref({
  id: '',
  nickname: '',
  userRole: '',
  userStatus: '0'
})

// 详情相关
const detailVisible = ref(false)
const userDetail = ref({})

// 表单验证规则
const formRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      match: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '邮箱格式不正确',
      trigger: 'blur'
    }
  ],
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      match: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,8}$/,
      message: '昵称需要是字母、数字、中文，且长度在1-8位',
      trigger: 'blur'
    }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'blur' }
  ]
}

// 重置查询表单
const resetPageForm = () => {
  pageFormRef.value.resetFields()
  createTime.value = ''
}

// 查询用户
const submitPageForm = (flag) => {
  if (flag === 1) {
    pageForm.value.currentPage = 1
  }
  if (createTime.value) {
    function convertToChinaTime(utcTimeString) {
      const utcDate = new Date(utcTimeString)
      utcDate.setHours(utcDate.getHours() + 8)
      return utcDate.toISOString()
    }
    pageForm.value.beginTime = convertToChinaTime(createTime.value[0])
    pageForm.value.endTime = convertToChinaTime(createTime.value[1])
  }
  tableLoading.value = true
  pageQueryUser(pageForm.value)
    .then(res => {
      if (res.data.code === 1) {
        tableData.value = res.data.data.records
        total.value = Number(res.data.data.total)
      } else {
        Message.error(res.data.message || '查询用户失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('查询用户失败')
    })
    .finally(() => {
      tableLoading.value = false
    })
}

// 分页处理
const pageChange = (currentPage) => {
  pageForm.value.currentPage = currentPage
  submitPageForm()
}

const pageSizeChange = (pageSize) => {
  pageForm.value.pageSize = pageSize
  submitPageForm()
}

// 新增用户
const handleAdd = () => {
  addVisible.value = true
  addForm.value = {
    nickname: '',
    userRole: '',
    userStatus: '0'
  }
}

// 新增取消
const handleAddCancel = () => {
  addVisible.value = false
  addFormRef.value?.resetFields()
}

// 新增确认
const handleAddOk = () => {
  addFormRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        const res = await saveUser(addForm.value)
        if (res.data.code === 1) {
          Message.success('新增用户成功')
          addVisible.value = false
          addFormRef.value?.resetFields()
          submitPageForm(1)
        } else {
          Message.error(res.data.message || '新增用户失败')
        }
      } catch (error) {
        console.error(error)
        Message.error('新增用户失败')
      }
    }
  })
}

// 编辑用户
const handleEdit = (record) => {
  getUser(record.id)
    .then(res => {
      if (res.data.code === 1) {
        const user = res.data.data
        editForm.value = {
          id: user.id,
          nickname: user.nickname,
          userRole: user.userRole,
          userStatus: user.userStatus.toString() // 转为字符串方便表单绑定
        }
        editVisible.value = true
      } else {
        Message.error(res.data.message || '获取用户详情失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('获取用户详情失败')
    })
}

// 编辑取消
const handleEditCancel = () => {
  editVisible.value = false
  editFormRef.value?.resetFields()
}

// 编辑确认
const handleEditOk = () => {
  editFormRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        const res = await updateUser(editForm.value)
        if (res.data.code === 1) {
          Message.success('编辑用户成功')
          editVisible.value = false
          editFormRef.value?.resetFields()
          submitPageForm()
        } else {
          Message.error(res.data.message || '编辑用户失败')
        }
      } catch (error) {
        console.error(error)
        Message.error('编辑用户失败')
      }
    }
  })
}

// 删除用户
const handleDelete = () => {
  if (selectedKeys.value.length === 0) {
    Message.warning('请先选择要删除的用户')
    return
  }

  deleteUser(selectedKeys.value) // 假设后端接收ids数组
    .then(res => {
      if (res.data.code === 1) {
        Message.success('删除用户成功')
        selectedKeys.value = []
        submitPageForm(1)
      } else {
        Message.error(res.data.message || '删除用户失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('删除用户失败')
    })
}

// 查看详情
const handleViewDetail = (id) => {
  getUser(id)
    .then(res => {
      if (res.data.code === 1) {
        userDetail.value = res.data.data
        detailVisible.value = true
      } else {
        Message.error(res.data.message || '获取用户详情失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('获取用户详情失败')
    })
}

onMounted(() => {
  submitPageForm()
})
</script>

<template>
  <div id="user-manager-page">
    <a-card class="card">
      <div class="set-container">
        <div class="select-container">
          <a-form :model="pageForm" layout="inline" ref="pageFormRef">
            <a-form-item label="用户id" field="id">
              <a-input v-model="pageForm.id" placeholder="请输入用户id"></a-input>
            </a-form-item>
            <a-form-item label="用户昵称" field="nickname">
              <a-input v-model="pageForm.nickname" placeholder="请输入用户昵称"></a-input>
            </a-form-item>
            <a-form-item label="用户角色" field="userRole">
              <a-select v-model="pageForm.userRole" placeholder="请选择用户角色">
                <a-option value="admin">管理员</a-option>
                <a-option value="user">普通用户</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="创建时间" field="beginTime">
              <a-range-picker
                showTime
                v-model="createTime"
                :time-picker-props="{ defaultValue: ['00:00:00', '00:00:00'] }"
                :format="'YYYY-MM-DDTHH:mm:ss'"
                style="width: 380px;"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="btn" @click="submitPageForm(1)">查询</a-button>
              <a-button type="outline" class="btn" @click="resetPageForm">重置</a-button>
            </a-form-item>
          </a-form>
        </div>
        <div class="button-container">
          <a-button type="primary" class="btn" @click="handleAdd">新增</a-button>
          <a-popconfirm
            content="确定要删除选中的用户吗？"
            @ok="handleDelete"
            position="br"
          >
            <a-button type="primary" status="danger" class="btn">删除</a-button>
          </a-popconfirm>
        </div>
      </div>
      <a-divider>用户管理</a-divider>
      <div class="table-container">
        <a-table
          stripe
          size="medium"
          :scroll="{ x: 1000 }"
          :loading="tableLoading"
          :pagination="false"
          row-key="id"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
          :columns="columns"
          :data="tableData"
        >
          <template #userStatusSlot="{ record }">
            <a-tag v-if="record.userStatus === '0'" color="green">正常</a-tag>
            <a-tag v-if="record.userStatus === '1'" color="red">禁用</a-tag>
          </template>
          <template #userRole="{ record }">
            <a-tag v-if="record.userRole === 'admin'" color="#165dff">管理员</a-tag>
            <a-tag v-if="record.userRole === 'user'" color="blue">普通用户</a-tag>
          </template>
          <template #optional="{ record }">
            <a-button type="text" status="success" @click="handleEdit(record)">编辑</a-button>
            <a-button type="text" @click="handleViewDetail(record.id)">详情</a-button>
          </template>
        </a-table>
      </div>
      <a-divider />
      <a-pagination
        show-total
        show-jumper
        show-page-size
        size="small"
        :total="total"
        :default-page-size="12"
        :current="pageForm.currentPage"
        :page-size="pageForm.pageSize"
        @change="pageChange"
        @page-size-change="pageSizeChange"
      />
    </a-card>

    <!-- 新增用户弹窗 -->
    <a-modal
      v-model:visible="addVisible"
      @cancel="handleAddCancel"
      @ok="handleAddOk"
      title="新增用户"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        hide-asterisk
      >
        <a-form-item field="email" hide-label>
          <a-input v-model="addForm.email" placeholder="请输入用户邮箱" />
        </a-form-item>
        <a-form-item field="nickname" hide-label>
          <a-input v-model="addForm.nickname" placeholder="请输入用户昵称" />
        </a-form-item>
        <a-form-item field="userRole" hide-label>
          <a-select v-model="addForm.userRole" placeholder="请选择用户角色">
            <a-option value="admin">管理员</a-option>
            <a-option value="user">普通用户</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="userStatus" hide-label>
          <a-radio-group v-model="addForm.userStatus">
            <a-radio value="0">正常</a-radio>
            <a-radio value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑用户弹窗 -->
    <a-modal
      v-model:visible="editVisible"
      @cancel="handleEditCancel"
      @ok="handleEditOk"
      title="编辑用户"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        hide-asterisk
      >
        <a-form-item field="nickname" hide-label>
          <a-input v-model="editForm.nickname" placeholder="请输入用户昵称" />
        </a-form-item>
        <a-form-item field="userRole" hide-label>
          <a-select v-model="editForm.userRole" placeholder="请选择用户角色">
            <a-option value="admin">管理员</a-option>
            <a-option value="user">普通用户</a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="userStatus" hide-label>
          <a-radio-group v-model="editForm.userStatus">
            <a-radio value="0">正常</a-radio>
            <a-tooltip content="禁用用户后，将同时下线该用户">
              <a-radio value="1">禁用</a-radio>
            </a-tooltip>
          </a-radio-group>
        </a-form-item>

      </a-form>
    </a-modal>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="用户详情"
      :footer="false"
    >
      <a-descriptions
        :column="1"
        :bordered="true"
        :size="'default'"
        :labelStyle="{ fontWeight: 'bold' }"
      >
        <a-descriptions-item label="用户ID">{{ userDetail.id }}</a-descriptions-item>
        <a-descriptions-item label="用户昵称">{{ userDetail.nickname }}</a-descriptions-item>
        <a-descriptions-item label="用户角色">
          <a-tag :color="userDetail.userRole === 'admin' ? '#165dff' : 'blue'">
            {{ userDetail.userRole === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="用户状态">
          <a-tag :color="userDetail.userStatus === '0' ? 'green' : 'red'">
            {{ userDetail.userStatus === '0' ? '正常' : '禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ userDetail.createTime }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{ userDetail.updateTime }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<style scoped>
.set-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.table-container {
  min-height: 60vh;
}

.select-container {
  width: 80%;
}

.select-container .btn, .button-container .btn {
  margin-right: 5px;
}
</style>
